package com.guhappy.stockutil;

// Generated Jul 19, 2011 6:12:32 PM by Hibernate Tools 3.4.0.CR1

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

/**
 * Home object for domain model class GlobalStocks.
 * @see  bd
 * @author  B.D
 */
public class GlobalStockHome {

	private static final Logger log = Logger.getLogger(GlobalStockHome.class);

	private static SessionFactory sessionFactory = getSessionFactory();

	protected static SessionFactory getSessionFactory() {
		sessionFactory = new Configuration().configure().buildSessionFactory();
		return sessionFactory;
	}

	public static void persist(GlobalStock transientInstance) {
		log.debug("persisting GlobalStocks instance");
		try {
			Session sess = sessionFactory.getCurrentSession();
			Transaction tran = sess.beginTransaction();
			sess.saveOrUpdate(transientInstance);
			tran.commit();
			/*sessionFactory.getCurrentSession().persist(transientInstance);*/
			log.debug("persist successful");
		} catch (StaleObjectStateException staleEx) {
			log.error("This interceptor does not implement optimistic concurrency control!");
			log.error("Your application will not work until you add compensation actions!");
            // Rollback, close everything, possibly compensate for any permanent changes
            // during the conversation, and finally restart business conversation. Maybe
            // give the user of the application a chance to merge some of his work with
            // fresh data... what you do here depends on your applications design.
            throw staleEx;
        } catch (Throwable ex) {
            // Rollback only
            ex.printStackTrace();
            try {
                if (sessionFactory.getCurrentSession().getTransaction().isActive()) {
                	log.debug("Trying to rollback database transaction after exception");
                	sessionFactory.getCurrentSession().getTransaction().rollback();
                }
            } catch (Throwable rbEx) {
                log.error("Could not rollback transaction after exception!", rbEx);
            }
        }
	}

	public static void attachDirty(GlobalStock instance) {
		log.debug("attaching dirty GlobalStocks instance");
		try {
			Session sess = sessionFactory.getCurrentSession();
			Transaction tran = sess.beginTransaction();
			sess.saveOrUpdate(instance);
			tran.commit();
			/*sessionFactory.getCurrentSession().saveOrUpdate(instance);*/
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static void attachClean(GlobalStock instance) {
		log.debug("attaching clean GlobalStocks instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static void delete(GlobalStock persistentInstance) {
		log.debug("deleting GlobalStocks instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public static GlobalStock merge(GlobalStock detachedInstance) {
		log.debug("merging GlobalStocks instance");
		try {
			GlobalStock result = (GlobalStock) sessionFactory.getCurrentSession()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public static GlobalStock findById(java.lang.String id) {
		log.debug("getting GlobalStocks instance with id: " + id);
		Session session=null;
		GlobalStock stock=null;
		try{
			session = sessionFactory.getCurrentSession();
			Query q = session.createQuery("from com.guhappy.model.user.GlobalStock c where c.id = :id");
			q.setString("id", id);
			stock=(GlobalStock) q.uniqueResult();
		}
		catch (Exception e){
			System.out.println(e);
			
		}
		return stock;
	}
	
	public static GlobalStock findByTicker(String ticker){
		GlobalStock stock = null;
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		stock = (GlobalStock) session.createCriteria(GlobalStock.class).add(Restrictions.eq("sticker", ticker.trim())).uniqueResult();
		return stock;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Object> updateAllStock(String regionindex)
	{
		
		List<Object> resultlist = new ArrayList<Object>();
		StringBuffer buf = new StringBuffer();
		buf.append("select ticker, name from ref_regionlist where regionindex = ").append(regionindex);
		try {
			Session session = sessionFactory.getCurrentSession();
			Transaction tran = session.beginTransaction();
			resultlist = session.createSQLQuery(buf.toString()).list();
			
		} catch (StaleObjectStateException staleEx) {
			log.error("This interceptor does not implement optimistic concurrency control!");
			log.error("Your application will not work until you add compensation actions!");
            // Rollback, close everything, possibly compensate for any permanent changes
            // during the conversation, and finally restart business conversation. Maybe
            // give the user of the application a chance to merge some of his work with
            // fresh data... what you do here depends on your applications design.
            throw staleEx;
        } catch (Throwable ex) {
            // Rollback only
            ex.printStackTrace();
            try {
                if (sessionFactory.getCurrentSession().getTransaction().isActive()) {
                	log.debug("Trying to rollback database transaction after exception");
                	sessionFactory.getCurrentSession().getTransaction().rollback();
                }
            } catch (Throwable rbEx) {
                log.error("Could not rollback transaction after exception!", rbEx);
            }
        }
		return resultlist;
	}
}
